package com.bl.weilan.dao.model.converter;

import com.bl.weilan.common.utils.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Strings;

import javax.persistence.AttributeConverter;

public abstract class JsonConverter implements AttributeConverter<Object, String> {


    /** ==============================
     *  Converter definition
     ** ============================== **/

    abstract TypeReference typeReference();

    @Override
    public String convertToDatabaseColumn(final Object attribute) {
        if (attribute == null) {
            return null;
        }
        return JSONUtil.jsonEncode(attribute);
    }

    @Override
    public Object convertToEntityAttribute(final String dbData) {
        if (Strings.isNullOrEmpty(dbData)) {
            return null;
        }
        return JSONUtil.decodeJson(dbData, typeReference());
    }

}
